﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Yunwei.WinSocket.Client
{
    public partial class Form1 : Form
    {
        Thread thread;
        Socket socket;
        string receivedMsg;
        Action<string> setMessageDelegate;
        public Form1()
        {
            InitializeComponent();

            setMessageDelegate = new Action<string>(this.setMessage);

            this.Load += Form1_Load; ;
            this.FormClosed += Form1_FormClosed;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            IPHostEntry ipHost = Dns.GetHostEntry("www.yunwei.com");

            IPAddress ipAddress = ipHost.AddressList[0];//IPAddress.Parse("socket.com");
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 9999);
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(ipEndPoint);

            thread = new Thread(ReceiveMsg);
            thread.IsBackground = true;
            thread.Start();
        }

        void ReceiveMsg()
        {
            try
            {
                while (socket.Connected)
                {
                    try
                    {
                        byte[] byteMessage = new byte[1024 * 1024 * 2];
                        int length = -1;

                        length = socket.Receive(byteMessage);

                        receivedMsg = Encoding.UTF8.GetString(byteMessage);

                        setMessageDelegate(receivedMsg);
                    }
                    catch (Exception ex)
                    {
                        setMessage("失败" + ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                setMessage("失败" + ex.Message);
            }
        }

        void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            socket.Shutdown(SocketShutdown.Receive);
            Thread.Sleep(100);
            socket.Close();
        }

        private void btnSendMsg_Click(object sender, EventArgs e)
        {
            try
            {
                if (!socket.Connected) setMessage("连接已断开");
                //string[] msgs = receivedMsg.Split('|');
                //string msg;
                //if (msgs.Length == 1)
                //    msg = receivedMsg;
                //else
                //    msg = string.Format("{0}|{1}", msgs[0], msgs[1]);
                string msg = tbMessage.Text;

                byte[] msgByte = Encoding.UTF8.GetBytes(msg);
                socket.Send(msgByte);
            }
            catch (Exception ex)
            {
            }
        }

        private void setMessage(string msg)
        {
            msg += "\r\n";
            try
            {
                if (tbMsgList.InvokeRequired)
                {
                    tbMsgList.Invoke(setMessageDelegate, msg);
                }
                else
                {
                    tbMsgList.AppendText("\r\n");
                    tbMsgList.AppendText(msg);
                }
            }
            catch (Exception ex)
            {
            }
        }
    }
}
